import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:xrenovation/api/project.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/custom_app_bar.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_date_picker.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';
import 'package:xrenovation/widgets/header_box.dart';
import 'package:xrenovation/widgets/rating_stars.dart';
import 'package:xrenovation/widgets/shadow_card.dart';

class TasksPage extends StatefulWidget {
  final String projectId;

  const TasksPage({super.key, required this.projectId});

  @override
  State<TasksPage> createState() => _TasksPageState();
}

class _TasksPageState extends State<TasksPage> {
  Map<String, dynamic>? projectData;
  List<dynamic> contractors = [];
  bool isLoading = true;
  bool isAddingTask = false;
  bool isUpdatingTask = false;

  // 控制器
  final nameController = TextEditingController();
  final descriptionController = TextEditingController();
  final expectedDaysController = TextEditingController();
  final budgetController = TextEditingController();
  final paymentAmountController = TextEditingController();

  // 状态变量
  DateTime? selectedStartDate;
  DateTime? selectedCompletionDate;
  String? selectedContractorId;
  double workQuality = 0;
  double workSpeed = 0;
  double costEffectiveness = 0;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    return HeaderBox(
      child: Scaffold(
        appBar: CustomAppBar(
          title: projectData?['name'] ?? localizations.translate('tasks_page_title'),
          actionName: localizations.translate('add_task'),
          actionIcon: Icons.add,
          action: () => _showAddTaskDialog(context),
        ),
        body: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          behavior: HitTestBehavior.opaque,
          child: isLoading ? const Center(child: CircularProgressIndicator()) : _buildBody(localizations, theme),
        ),
      ),
    );
  }

  @override
  void dispose() {
    nameController.dispose();
    descriptionController.dispose();
    expectedDaysController.dispose();
    budgetController.dispose();
    paymentAmountController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _addTask() async {
    if (nameController.text.isEmpty) return;

    try {
      final res = await ProjectApi.addTask({
        'name': nameController.text,
        'description': descriptionController.text,
        'projectId': widget.projectId,
        'startDate': selectedStartDate?.millisecondsSinceEpoch.toString(),
        'expectedDays': expectedDaysController.text,
        'budget': budgetController.text,
        'contractorId': selectedContractorId,
      });

      if (res['code'] == 200) {
        MessageUtil.success('Task added successfully');
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to add task');
      }
    } catch (e) {
      MessageUtil.error('Failed to add task');
    }
  }

  Widget _buildBody(AppLocalizations localizations, ThemeData theme) {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
      child: Column(
        children: [
          if (projectData != null) _buildProjectCard(localizations, theme),
          const SizedBox(height: 28),
          if (projectData == null || (projectData?['tasks'] as List?)?.isNotEmpty != true)
            Center(
              child: Text(
                localizations.translate('no_tasks'),
                style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
                textAlign: TextAlign.center,
              ),
            ),
          if (projectData != null && (projectData?['tasks'] as List?)?.isNotEmpty == true)
            ...projectData!['tasks'].map<Widget>(
              (task) => Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: _buildTaskCard(task, localizations, theme),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildContractorDropdown({
    required String? selectedContractorId,
    required List<dynamic> contractors,
    required ValueChanged<String?> onChanged,
    required AppLocalizations localizations,
    required ThemeData theme,
  }) {
    final double screenWidth = MediaQuery.of(context).size.width;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          localizations.translate('contractor'),
          style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          value: selectedContractorId,
          hint: Text(
            localizations.translate('select_contractor'),
            style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.4)),
          ),
          decoration: InputDecoration(
            border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(8))),
            contentPadding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: theme.colorScheme.outline.withOpacity(0.5)),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: theme.colorScheme.primary, width: 1.5),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: theme.colorScheme.error),
            ),
          ),
          items:
              contractors.map<DropdownMenuItem<String>>((contractor) {
                final skills = contractor['skills'] as List? ?? [];
                final displayText =
                    '${contractor['firstName']} ${contractor['lastName']}'
                    '${skills.isNotEmpty ? ' (${skills.map((s) => s['name']).join('、')})' : ''}';

                return DropdownMenuItem<String>(
                  value: contractor['id'],
                  child: Container(
                    constraints: BoxConstraints(maxWidth: screenWidth - 110),
                    child: Text(displayText, maxLines: 1, overflow: TextOverflow.ellipsis),
                  ),
                );
              }).toList(),
          onChanged: onChanged,
        ),
      ],
    );
  }

  Widget _buildDialogHeader(String title, String subtitle, ThemeData theme, VoidCallback onClose) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(title, style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
              const SizedBox(height: 8),
              Text(subtitle, style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor)),
            ],
          ),
        ),
        IconButton(icon: const Icon(Icons.close), onPressed: onClose),
      ],
    );
  }

  Widget _buildProgressRow({
    required String label,
    required String value,
    required double progress,
    required Color color,
    required String description,
    required ThemeData theme,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [Text(label, style: theme.textTheme.bodyMedium), Text(value, style: theme.textTheme.bodyMedium)],
        ),
        const SizedBox(height: 8),
        SizedBox(
          height: 8,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: progress,
              backgroundColor: theme.colorScheme.primary.withOpacity(0.1),
              valueColor: AlwaysStoppedAnimation<Color>(color),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(description, style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor)),
      ],
    );
  }

  Widget _buildProjectCard(AppLocalizations localizations, ThemeData theme) {
    final tasks = projectData?['tasks'] as List? ?? [];
    final symbol = projectData?['symbol'] ?? '\$';
    final totalPaid = tasks.fold<double>(0, (sum, task) => sum + (task['paymentAmount'] ?? 0));
    final budget = tasks.fold<double>(0, (sum, task) => sum + (task['budget'] ?? 0));
    final completedTasks = tasks.where((t) => t['status'] == 1).length;
    final progress = tasks.isEmpty ? 0.0 : completedTasks / tasks.length;
    final budgetProgress = budget == 0 ? 0.0 : totalPaid / budget;

    return ShadowCard(
      color: theme.cardColor.withOpacity(0.5),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(projectData?['description'] ?? '', style: theme.textTheme.bodyLarge),
            const SizedBox(height: 20),
            _buildProgressRow(
              label: localizations.translate('overall_progress'),
              value: '${(progress * 100).toStringAsFixed(0)}% ${localizations.translate('complete')}',
              progress: progress,
              color: const Color(0xFF155DFC),
              description: localizations
                  .translate('tasks_completed')
                  .replaceAll('{completed}', '$completedTasks')
                  .replaceAll('{total}', '${tasks.length}'),
              theme: theme,
            ),
            const SizedBox(height: 20),
            _buildProgressRow(
              label: localizations.translate('budget'),
              value: '$symbol${totalPaid.toStringAsFixed(2)} / $symbol${budget.toStringAsFixed(2)}',
              progress: budgetProgress,
              color: const Color(0xFF00C951),
              description: localizations
                  .translate('remaining')
                  .replaceAll('{amount}', '$symbol${(budget - totalPaid).toStringAsFixed(2)}'),
              theme: theme,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRatingRow({
    required String label,
    required double value,
    required ValueChanged<double> onChanged,
    required ThemeData theme,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(children: [Text(label, style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500))]),
        const SizedBox(height: 8),
        Row(
          children: [
            RatingStars(
              rating: value,
              onRatingChanged: onChanged,
              starSize: 28,
              selectedColor: const Color(0xFFFDC700),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildTaskCard(dynamic task, AppLocalizations localizations, ThemeData theme) {
    final isDarkMode = theme.brightness == Brightness.dark;
    final isCompleted = task['status'] == 1;
    final isOverTime = _isTaskOverdue(task);
    final symbol = projectData?['symbol'] ?? '\$';
    final startDate = task['startDate'] != null ? DateTime.parse(task['startDate']).toLocal() : null;
    final expectedDays = task['expectedDays'] as int?;
    final dueDate = startDate != null && expectedDays != null ? startDate.add(Duration(days: expectedDays)) : null;
    final completionDate = task['completionDate'] != null ? DateTime.parse(task['completionDate']).toLocal() : null;

    return ShadowCard(
      padding: const EdgeInsets.fromLTRB(6, 12, 12, 12),
      color: isOverTime ? (isDarkMode ? const Color(0xFF210C0F) : const Color(0xFFFFE2E2)) : null,
      onTap: () => _showEditTaskDialog(task['id']),
      child: Padding(
        padding: const EdgeInsets.all(0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            IconButton(
              icon: Icon(
                isCompleted ? Icons.check_circle : Icons.radio_button_unchecked,
                color: isCompleted ? Colors.green : theme.colorScheme.onSurface.withOpacity(0.6),
              ),
              onPressed: null,
            ),
            const SizedBox(width: 0),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            Text(
                              task['name'] ?? '',
                              style: theme.textTheme.titleMedium?.copyWith(
                                decoration: isCompleted ? TextDecoration.lineThrough : null,
                                color: isCompleted ? theme.hintColor : null,
                              ),
                            ),
                            if (isOverTime) ...[
                              const SizedBox(width: 10),
                              Icon(Icons.calendar_today, size: 16, color: theme.colorScheme.error),
                              const SizedBox(width: 6),
                              Text(
                                localizations.translate('overdue'),
                                style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.error),
                              ),
                            ],
                          ],
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => _showDeleteDialog(task['id'], localizations),
                      ),
                    ],
                  ),
                  if (task['description'] != null && task['description'].isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Text(task['description'], style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor)),
                  ],
                  if (startDate != null) ...[
                    const SizedBox(height: 12),
                    _buildTaskDetailRow(
                      icon: Icons.calendar_today,
                      text:
                          '${localizations.translate('start')}: ${DateFormat('yyyy/MM/dd').format(startDate)}'
                          '${dueDate != null ? ' (${localizations.translate('due')}: ${DateFormat('yyyy/MM/dd').format(dueDate)})' : ''}',
                      color: isOverTime ? theme.colorScheme.error : theme.hintColor,
                      theme: theme,
                    ),
                  ],
                  if (expectedDays != null) ...[
                    const SizedBox(height: 8),
                    _buildTaskDetailRow(
                      icon: Icons.access_time,
                      text: '${localizations.translate('duration')}: $expectedDays ${localizations.translate('days')}',
                      theme: theme,
                    ),
                  ],
                  if (task['budget'] != null) ...[
                    const SizedBox(height: 8),
                    _buildTaskDetailRow(
                      icon: Icons.attach_money,
                      text: '${localizations.translate('budget')}: $symbol${task['budget']}',
                      theme: theme,
                    ),
                  ],
                  if (task['paymentAmount'] != null) ...[
                    const SizedBox(height: 8),
                    _buildTaskDetailRow(
                      icon: Icons.payment,
                      text: '${localizations.translate('payment')}: $symbol${task['paymentAmount']}',
                      theme: theme,
                    ),
                  ],
                  if (completionDate != null) ...[
                    const SizedBox(height: 8),
                    _buildTaskDetailRow(
                      icon: Icons.done_all,
                      text:
                          '${localizations.translate('completed')}: ${DateFormat('yyyy/MM/dd').format(completionDate)}',
                      theme: theme,
                    ),
                  ],
                  if (task['workQuality'] != null ||
                      task['workSpeed'] != null ||
                      task['costEffectiveness'] != null) ...[
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        if (task['workQuality'] != null)
                          Text(
                            '${localizations.translate('quality')}: ${task['workQuality']}/5',
                            style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
                          ),
                        if (task['workSpeed'] != null)
                          Text(
                            '${localizations.translate('speed')}: ${task['workSpeed']}/5',
                            style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
                          ),
                        if (task['costEffectiveness'] != null)
                          Text(
                            '${localizations.translate('value')}: ${task['costEffectiveness']}/5',
                            style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
                          ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTaskDetailRow({required IconData icon, required String text, Color? color, required ThemeData theme}) {
    return Row(
      children: [
        Icon(icon, size: 16, color: color ?? theme.hintColor),
        const SizedBox(width: 8),
        Text(text, style: theme.textTheme.bodySmall?.copyWith(color: color ?? theme.hintColor)),
      ],
    );
  }

  Future<void> _deleteTask(String taskId, AppLocalizations localizations) async {
    final confirmed = await MessageUtil.showConfirmDialog(
      title: localizations.translate('delete_confirm_title'),
      message: localizations.translate('delete_confirm_content'),
      confirmText: localizations.translate('delete'),
      cancelText: localizations.translate('cancel'),
      confirmColor: Theme.of(context).colorScheme.error,
    );

    if (confirmed != true) return;

    final closeLoading = MessageUtil.loading(localizations.translate('deleting'));
    try {
      final res = await ProjectApi.deleteTask(taskId);
      closeLoading();

      if (res['code'] == 200) {
        MessageUtil.success(localizations.translate('delete_success'));
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to delete task');
      }
    } catch (e) {
      closeLoading();
      MessageUtil.error('Failed to delete task');
    }
  }

  bool _isTaskOverdue(dynamic task) {
    if (task['status'] == 1) return false;
    if (task['startDate'] == null || task['expectedDays'] == null) return false;

    try {
      final startDate = DateTime.parse(task['startDate']);
      final expectedDays = task['expectedDays'] as int;
      final dueDate = startDate.add(Duration(days: expectedDays));
      return dueDate.isBefore(DateTime.now());
    } catch (e) {
      return false;
    }
  }

  Future<void> _loadData() async {
    setState(() => isLoading = true);
    try {
      final tasksRes = await ProjectApi.getProjectTasks(widget.projectId);
      final contractorsRes = await ProjectApi.getContractorList();

      if (mounted) {
        setState(() {
          projectData = tasksRes['data'];
          contractors = contractorsRes['data'] ?? [];
          isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => isLoading = false);
        MessageUtil.error('Failed to load tasks');
      }
    }
  }

  void _showAddTaskDialog(BuildContext context) {
    final formKey = GlobalKey<FormState>();
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    // 重置表单状态
    nameController.clear();
    descriptionController.clear();
    expectedDaysController.clear();
    budgetController.clear();
    selectedStartDate = null;
    selectedContractorId = null;

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              behavior: HitTestBehavior.opaque,
              child: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Container(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildDialogHeader(
                        localizations.translate('add_new_task'),
                        localizations.translate('create_task_desc'),
                        theme,
                        () => Navigator.pop(context),
                      ),
                      const SizedBox(height: 24),
                      Expanded(
                        child: SingleChildScrollView(
                          child: Form(
                            key: formKey,
                            child: Column(
                              children: [
                                CustomTextField(
                                  controller: nameController,
                                  label: localizations.translate('task_name'),
                                  labelMark: true,
                                  hintText: localizations.translate('task_name_hint'),
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return localizations.translate('task_name_required');
                                    }
                                    return null;
                                  },
                                ),
                                const SizedBox(height: 16),
                                CustomTextField(
                                  controller: descriptionController,
                                  label: localizations.translate('project_description'),
                                  hintText: localizations.translate('project_description_hint'),
                                  maxLines: 3,
                                ),
                                const SizedBox(height: 16),
                                CustomDatePicker(
                                  label: localizations.translate('start_date'),
                                  hintText: localizations.translate('select_date_hint'),
                                  selectedDate: selectedStartDate,
                                  onDateSelected: (date) {
                                    setState(() {
                                      selectedStartDate = date;
                                    });
                                  },
                                ),
                                const SizedBox(height: 16),
                                CustomTextField(
                                  controller: expectedDaysController,
                                  label: localizations.translate('expected_days'),
                                  hintText: localizations.translate('expected_days_hint'),
                                  keyboardType: TextInputType.number,
                                  maxLength: 4,
                                ),
                                const SizedBox(height: 16),
                                CustomTextField(
                                  controller: budgetController,
                                  keyboardType: TextInputType.number,
                                  label: localizations.translate('budget'),
                                  hintText: localizations.translate('budget_hint'),
                                  prefixText: projectData?['symbol'] ?? '\$',
                                ),
                                const SizedBox(height: 16),
                                if (contractors.isNotEmpty)
                                  _buildContractorDropdown(
                                    selectedContractorId: selectedContractorId,
                                    contractors: contractors,
                                    onChanged: (value) => setState(() => selectedContractorId = value),
                                    localizations: localizations,
                                    theme: theme,
                                  ),
                                const SizedBox(height: 40),
                                CustomButton(
                                  title: localizations.translate('add_close'),
                                  isLoading: isAddingTask,
                                  onTap: () async {
                                    if (formKey.currentState?.validate() ?? false) {
                                      setState(() => isAddingTask = true);
                                      await _addTask();
                                      if (mounted) {
                                        setState(() => isAddingTask = false);
                                        Navigator.pop(context);
                                      }
                                    }
                                  },
                                ),
                                const SizedBox(height: 10),
                                CustomButton(
                                  title: localizations.translate('add_continue'),
                                  isLoading: isAddingTask,
                                  onTap: () async {
                                    if (formKey.currentState?.validate() ?? false) {
                                      setState(() => isAddingTask = true);
                                      await _addTask();
                                      if (mounted) {
                                        nameController.clear();
                                        descriptionController.clear();
                                        expectedDaysController.clear();
                                        budgetController.clear();
                                        setState(() {
                                          selectedStartDate = null;
                                          selectedContractorId = null;
                                          isAddingTask = false;
                                        });
                                      }
                                    }
                                  },
                                ),
                                const SizedBox(height: 10),
                                CustomButton(
                                  title: localizations.translate('cancel'),
                                  isOutlined: true,
                                  onTap: () => Navigator.pop(context),
                                ),
                                const SizedBox(height: 30),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  void _showDeleteDialog(String taskId, AppLocalizations localizations) {
    _deleteTask(taskId, localizations);
  }

  void _showEditTaskDialog(String taskId) async {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final closeLoading = MessageUtil.loading(localizations.translate('Loading'));

    try {
      final res = await ProjectApi.getTaskDetails(taskId);
      closeLoading();
      if (res['code'] != 200) {
        MessageUtil.error(res['message'] ?? 'Failed to load task details');
        return;
      }

      final taskData = res['data'];
      nameController.text = taskData['name'] ?? '';
      descriptionController.text = taskData['description'] ?? '';
      expectedDaysController.text = taskData['expectedDays']?.toString() ?? '';
      budgetController.text = taskData['budget']?.toString() ?? '';
      paymentAmountController.text = taskData['paymentAmount']?.toString() ?? '';
      selectedStartDate = taskData['startDate'] != null ? DateTime.parse(taskData['startDate']).toLocal() : null;
      selectedCompletionDate =
          taskData['completionDate'] != null ? DateTime.parse(taskData['completionDate']).toLocal() : null;
      selectedContractorId = taskData['contractorId'];
      workQuality = taskData['workQuality']?.toDouble() ?? 0;
      workSpeed = taskData['workSpeed']?.toDouble() ?? 0;
      costEffectiveness = taskData['costEffectiveness']?.toDouble() ?? 0;

      if (!mounted) return;

      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        builder: (context) {
          return StatefulBuilder(
            builder: (context, setState) {
              return GestureDetector(
                onTap: () => FocusScope.of(context).unfocus(),
                behavior: HitTestBehavior.opaque,
                child: Padding(
                  padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Container(
                    padding: const EdgeInsets.all(24),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildDialogHeader(
                          localizations.translate('task_details'),
                          localizations.translate('fill_task_details'),
                          theme,
                          () => Navigator.pop(context),
                        ),
                        const SizedBox(height: 16),
                        Text(taskData['name'], style: theme.textTheme.titleMedium),
                        if (taskData['description'] != null && taskData['description'].isNotEmpty) ...[
                          const SizedBox(height: 8),
                          Text(
                            taskData['description'],
                            style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                          ),
                        ],
                        const SizedBox(height: 16),
                        Expanded(
                          child: SingleChildScrollView(
                            child: Form(
                              child: Column(
                                children: [
                                  CustomDatePicker(
                                    label: localizations.translate('start_date'),
                                    hintText: localizations.translate('select_date_hint'),
                                    selectedDate: selectedStartDate,
                                    onDateSelected: (date) {
                                      setState(() {
                                        selectedStartDate = date;
                                      });
                                    },
                                  ),
                                  const SizedBox(height: 16),
                                  CustomTextField(
                                    controller: expectedDaysController,
                                    label: localizations.translate('expected_days'),
                                    hintText: localizations.translate('expected_days_hint'),
                                    keyboardType: TextInputType.number,
                                    maxLength: 4,
                                  ),
                                  const SizedBox(height: 16),
                                  CustomTextField(
                                    controller: budgetController,
                                    keyboardType: TextInputType.number,
                                    label: localizations.translate('budget'),
                                    hintText: localizations.translate('budget_hint'),
                                    prefixText: projectData?['symbol'] ?? '\$',
                                  ),
                                  const SizedBox(height: 16),
                                  if (contractors.isNotEmpty)
                                    _buildContractorDropdown(
                                      selectedContractorId: selectedContractorId,
                                      contractors: contractors,
                                      onChanged: (value) => setState(() => selectedContractorId = value),
                                      localizations: localizations,
                                      theme: theme,
                                    ),
                                  const SizedBox(height: 16),
                                  CustomDatePicker(
                                    label: localizations.translate('completion_date'),
                                    hintText: localizations.translate('select_date_hint'),
                                    selectedDate: selectedCompletionDate,
                                    onDateSelected: (date) {
                                      setState(() {
                                        selectedCompletionDate = date;
                                      });
                                    },
                                  ),
                                  const SizedBox(height: 16),
                                  CustomTextField(
                                    controller: paymentAmountController,
                                    keyboardType: TextInputType.number,
                                    label: localizations.translate('payment_amount'),
                                    hintText: localizations.translate('payment_amount_hint'),
                                    prefixText: projectData?['symbol'] ?? '\$',
                                  ),
                                  const SizedBox(height: 22),
                                  _buildRatingRow(
                                    label: localizations.translate('work_quality'),
                                    value: workQuality,
                                    onChanged: (value) => setState(() => workQuality = value),
                                    theme: theme,
                                  ),
                                  const SizedBox(height: 22),
                                  _buildRatingRow(
                                    label: localizations.translate('work_speed'),
                                    value: workSpeed,
                                    onChanged: (value) => setState(() => workSpeed = value),
                                    theme: theme,
                                  ),
                                  const SizedBox(height: 22),
                                  _buildRatingRow(
                                    label: localizations.translate('cost_effectiveness'),
                                    value: costEffectiveness,
                                    onChanged: (value) => setState(() => costEffectiveness = value),
                                    theme: theme,
                                  ),
                                  const SizedBox(height: 40),
                                  CustomButton(
                                    title: localizations.translate('save_changes'),
                                    isLoading: isUpdatingTask,
                                    onTap: () async {
                                      setState(() => isUpdatingTask = true);
                                      await _updateTask(taskId);
                                      if (mounted) {
                                        Navigator.pop(context);
                                        setState(() => isUpdatingTask = false);
                                      }
                                    },
                                  ),
                                  const SizedBox(height: 10),
                                  CustomButton(
                                    title: localizations.translate('cancel'),
                                    isOutlined: true,
                                    onTap: () => Navigator.pop(context),
                                  ),
                                  const SizedBox(height: 30),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          );
        },
      );
    } catch (e) {
      closeLoading();
      if (mounted) {
        MessageUtil.error('Failed to load task details');
      }
    }
  }

  Future<void> _updateTask(String taskId) async {
    try {
      final res = await ProjectApi.updateTask({
        'id': taskId,
        'projectId': widget.projectId,
        'name': nameController.text,
        'description': descriptionController.text,
        'startDate': selectedStartDate?.millisecondsSinceEpoch.toString(),
        'expectedDays': expectedDaysController.text,
        'budget': budgetController.text,
        'contractorId': selectedContractorId,
        'completionDate': selectedCompletionDate?.millisecondsSinceEpoch.toString(),
        'paymentAmount': paymentAmountController.text,
        'workQuality': workQuality,
        'workSpeed': workSpeed,
        'costEffectiveness': costEffectiveness,
      });

      if (res['code'] == 200) {
        MessageUtil.success('Task updated successfully');
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to update task');
      }
    } catch (e) {
      MessageUtil.error('Failed to update task');
    }
  }
}
